<template>
  <div class="change-password-container">
    <el-card class="header-card">
      <h2><el-icon><Lock /></el-icon> 修改密码</h2>
    </el-card>

    <el-card>
      <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
        label-width="120px"
        class="password-form"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入旧密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleChangePassword" :loading="submitting">
            确认修改
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { Lock } from '@element-plus/icons-vue';
import { changePassword, verifyUserPassword } from '@/api/user';
import { useUserStore } from '@/stores/user';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';

const router = useRouter();
const userStore = useUserStore();

const submitting = ref(false);
const passwordFormRef = ref<FormInstance>();

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 验证确认密码
const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'));
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

const passwordRules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ]
};

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return;
  
  await passwordFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    if (!userStore.userId || !userStore.user?.username) {
      ElMessage.warning('请先登录');
      return;
    }

    submitting.value = true;
    try {
      // 首先验证旧密码（使用和登录一样的验证接口）
      const verifyResponse = await verifyUserPassword(
        userStore.user.username,
        passwordForm.oldPassword
      );

      if (verifyResponse.operateResult !== 'SUCC') {
        ElMessage.error(verifyResponse.errorMsg || '旧密码验证失败');
        return;
      }

      // 旧密码验证通过后，修改密码
      const response = await changePassword(
        userStore.userId,
        passwordForm.oldPassword,
        passwordForm.newPassword
      );

      if (response.operateResult === 'SUCC') {
        ElMessage.success('密码修改成功，请重新登录');
        // 清空表单
        resetForm();
        // 退出登录
        setTimeout(() => {
          userStore.logout();
          router.push('/login');
        }, 1500);
      } else {
        ElMessage.error(response.errorMsg || '密码修改失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '密码修改失败');
    } finally {
      submitting.value = false;
    }
  });
};

// 重置表单
const resetForm = () => {
  passwordFormRef.value?.resetFields();
};
</script>

<style scoped>
.change-password-container {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.header-card {
  margin-bottom: 20px;
}

.header-card h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #303133;
}

.password-form {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px 0;
}

</style>
